﻿using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BCCServer.Common.Common
{
     public  class RedisHelper
    {
        private static string RedisConnectionSTR = "localhost:6379";
        private static object RedisLock = new object();
        private static ConnectionMultiplexer RedisInstance = null;


        public static ConnectionMultiplexer Instance
        {
            get
            {
                if (RedisInstance == null)
                {
                    lock (RedisLock)
                    {
                        if (RedisInstance == null || RedisInstance.IsConnected == false)
                        {
                            RedisInstance = ConnectionMultiplexer.Connect(RedisConnectionSTR);
                        }
                    }
                }


                return RedisInstance;
            }  //end get
        }


        public static IDatabase GetRedisDatabase()
        {
            return Instance.GetDatabase();
        }


        public static void AddKeyValue(string k, string v)
        {
            TimeSpan span = DateTime.Now.AddMinutes(2) - DateTime.Now;
            GetRedisDatabase().StringSet(k, v, span);
        }


        public static string GetKeyValue(string k)
        {
            return GetRedisDatabase().StringGet(k);
        }

        public static bool RemoveKeyValue(string k) 
        {
            return GetRedisDatabase().KeyDelete(k);
        }

        /// <summary>
        /// 执行lua脚本
        /// </summary>
        /// <param name="luaScript"></param>
        /// <param name="productKey"></param>
        /// <returns></returns>
        public static bool ScriptEvaluateLua(string luaScript, string productKey)
        {
            RedisResult result = GetRedisDatabase().ScriptEvaluate(luaScript, new RedisKey[] { productKey });
            if ((int)result == 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
